package com.wsd.smartcarwasher.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wsd.smartcarwasher.domain.Partner;
import com.wsd.smartcarwasher.domain.UserFromH5CouponRecord;
import com.wsd.smartcarwasher.domain.UserFromH5CouponRecordExample;
import com.wsd.smartcarwasher.service.*;
import com.wsd.smartcarwasher.util.ReturnUtil;
import com.wsd.smartcarwasher.util.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
public class TestController {
    private Logger logger = LoggerFactory.getLogger(TestController.class);

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private MqttService mqttService;
    @Resource
    private AdminService adminService;
    @Resource
    private OrderService orderService;
    @Resource
    private UserFromH5CouponRecordService userFromH5CouponRecordService;

    @RequestMapping(value = "/v1/login", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object login(@RequestBody Partner partner) {
        Map<String, Object> jsonObject = new HashMap<>();
        Subject subject = SecurityUtils.getSubject();

//        UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUsername(), userInfo.getPassword());
        try {
            if (!subject.isAuthenticated()) {
                UsernamePasswordToken token = new UsernamePasswordToken(partner.getUsername(), partner.getPassword());
                token.setRememberMe(true);
                subject.login(token);
            }

            jsonObject.put("token", subject.getSession().getId());
            jsonObject.put("msg", "登录成功");
        } catch (IncorrectCredentialsException e) {
            jsonObject.put("msg", "密码错误");
        } catch (LockedAccountException e) {
            jsonObject.put("msg", "登录失败，该用户已被冻结");
        } catch (AuthenticationException e) {
            jsonObject.put("msg", "该用户不存在");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    @RequestMapping(value = "/v1/to_login")
    @ResponseBody
    public Object toLogin() {
        return "please change to page login";
    }

    //注解的使用
    @RequiresRoles(value = {"admin"}, logical = Logical.AND)
    @RequiresPermissions(value = {"create"}, logical = Logical.AND)
    @RequestMapping(value = "/v1/add_goods", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object addGoods(@RequestBody Map<String, Object> userInfo) {
        Map<String, String> resultMap = new HashMap<>();
        Subject subject = SecurityUtils.getSubject();
        String result = "验证通过";
//        if(subject.hasRole("admin")) {
//            try {
//                subject.checkPermissions("add");
//            }catch (UnauthorizedException e){
//                result = "权限不足";
//                logger.info("错误信息："+e.getMessage());
//                logger.info("权限不足");
//            }
//        } else {
//            result = "not required role";
//        }

        resultMap.put("result", result);
        return resultMap;
    }

    @RequestMapping(value = "/v1/403")
    @ResponseBody
    public Object noPermission(@RequestBody Map<String, Object> userInfo) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("result", "noPermission");
        return resultMap;
    }

    @RequestMapping(value = "/v2/user_info", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object findByUsername(@RequestParam("username") String username) {
        if (StringUtil.isEmpty(username)) {
            return "username is empty";
        }
        return userInfoService.findByUsername(username);
    }

    //推送数据接口
    @ResponseBody
    @RequestMapping(value = "/socket/push/{userId}", method = RequestMethod.POST)
    public ModelMap pushToWeb(@PathVariable String userId, @RequestBody String message) {
        WebSocketServer.sendInfo(message,userId);
        return ReturnUtil.Success("发送消息失败", userId);
    }

    //推送数据接口
//    @ResponseBody
//    @RequestMapping(value = "/v1/c", method = RequestMethod.POST)
//    public ModelMap pu() {
//        String beforePayTime=this.orderService.queryByLatelyUserId("order_00JcIqDHqNJoxkF3q1MEPlp9BH");
//        if(beforePayTime!=null)
//        {
//            System.out.println(beforePayTime);
//            Date beforeTime= DateUtil.convertStringToDate(beforePayTime);
//            int days = (int) ((new Date().getTime() - beforeTime.getTime()) / (1000*3600*24));
//            System.out.println("days"+days);
//            this.orderService.updatePayNode("order_00JcIqDHqNJoxkF3q1MEPlp9BH",days);
//        }
//        return ReturnUtil.Success("发送消息失败");
//    }

    //推送数据接口
    @ResponseBody
    @RequestMapping(value = "/v1/testMethod", method = RequestMethod.GET)
    public ModelMap test() {



        return ReturnUtil.Success("发送消息失败", this.userFromH5CouponRecordService.selectH5CouponByMobile("13629189683"));
    }


}
